#include "widget.h"
#include "ui_widget.h"
#include "QFileDialog"
#include "QDebug"

#include "QtSerialPort/QSerialPort"
#include "QtSerialPort/QSerialPortInfo"

#include "QTimer"
#include "QMessageBox"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_UpdateFilePath = "";
    m_ComName = "";

    m_PendingBySending = false;
    m_SerialPort = new QSerialPort();

    m_TimerScanComInfo = new QTimer(this);
    connect(m_TimerScanComInfo,SIGNAL(timeout()),this,SLOT(pSlotUpdatecominfo()));
    m_TimerScanComInfo->start(50);
}

Widget::~Widget()
{
    delete m_TimerScanComInfo;
    delete ui;
    m_SerialPort->close();
    delete m_SerialPort;
}

void Widget::pSlotUpdatecominfo()
{
    if(m_SerialPort!=NULL)
    {
        for(QSerialPortInfo info :QSerialPortInfo::availablePorts())
        {
            bool isFinded = false;
            for(int i32Num = 0;i32Num < ui->comNum->count();i32Num++)
            {
                if(ui->comNum->itemText(i32Num) == info.portName())
                {
                    isFinded = true;
                    break;
                }
            }

            if(!isFinded)
            {
                qDebug()<<"INSERT:"<<info.portName();
                ui->comNum->addItem(info.portName());
            }

        }

        for(int i32Num = 0;i32Num < ui->comNum->count();i32Num++)
        {
            bool isFinded = false;
            for(QSerialPortInfo info :QSerialPortInfo::availablePorts())
            {
                if(info.portName() == ui->comNum->itemText(i32Num))
                {
                    isFinded = true;
                    break;
                }
            }
            if(!isFinded)
            {
                qDebug()<<"REMOVE:"<<ui->comNum->itemText(i32Num);
                ui->comNum->removeItem(i32Num);
                i32Num = i32Num - 1;
            }
        }
    }
    m_ComName = ui->comNum->currentText();

    if(m_ComName!=NULL && m_UpdateFilePath!=NULL )
    {
        if(!ui->cmd->isEnabled())
        {
            ui->cmd->setEnabled(true);
        }
    }
    else {
        if(ui->cmd->isEnabled())
        {
            ui->cmd->setEnabled(false);
        }
    }
}


void Widget::on_selectUpdateFile_clicked()
{
    QString qstrTemp = QFileDialog::getOpenFileName(this,"选择升级文件","","升级文件(*.bin);;所有文件(*.*)");

    if(qstrTemp.length()>2)
    {
        m_UpdateFilePath = qstrTemp;
        ui->selectUpdateFile->setText(m_UpdateFilePath);
        qDebug()<<m_UpdateFilePath;
        /*check file Effective*/

        /*check Finished*/
        ui->cmd->setEnabled(true);
    }
}

void Widget::on_cmd_clicked()
{

    m_SerialPort->setPortName(m_ComName);
    m_SerialPort->setBaudRate(115200);
    m_SerialPort->setDataBits(QSerialPort::Data8);
    m_SerialPort->setParity(QSerialPort::NoParity);
    m_SerialPort->setStopBits(QSerialPort::OneStop);
    m_SerialPort->setFlowControl(QSerialPort::NoFlowControl);
    m_SerialPort->setReadBufferSize(10);


    if(m_SerialPort->open(QIODevice::ReadWrite))
    {
        m_TimerScanComInfo->stop();
        qDebug()<<"串口打开成功!";
        ui->cmd->setText("请等待...");
        ui->cmd->setEnabled(false);
        ui->comNum->setEnabled(false);
        ui->selectUpdateFile->setEnabled(false);
        QObject::connect(m_SerialPort, &QSerialPort::readyRead, this, &Widget::SerialPortRecvMsgEvent);
        SerialPortDataSend();
        ui->cmd->setText("发送成功...");
        ui->cmd->setEnabled(true);
        ui->comNum->setEnabled(true);
        ui->selectUpdateFile->setEnabled(true);
        m_SerialPort->close();
    }
    else {
        QMessageBox::warning(this,tr("警告"),tr("串口打开失败，请重试!"),QMessageBox::Ok);
    }
}

void Widget::SerialPortRecvMsgEvent()
{
    QString mRec(m_SerialPort->readAll());
    qDebug()<<mRec;
    ui->receiveMsg->setText(mRec);
    //        m_SerialPort->close();
    //        ui->cmd->setText("开始");
    //        ui->cmd->setEnabled(true);
    //        ui->comNum->setEnabled(true);
    //        ui->selectUpdateFile->setEnabled(true);
    //ui->progress->setValue(10);
}

void Widget::SerialPortDataSend()
{
    if(m_SerialPort!=NULL)
    {
        QFile file(m_UpdateFilePath);
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray fileTmp = file.readAll();

        if(fileTmp.length()<10)
        {
           QMessageBox::warning(this,tr("警告"),tr("文件长度错误!"),QMessageBox::Ok);
           return;
        }

        int tony = (((int)(fileTmp.length()*0.01))+(fileTmp.length()%100)>0);

        for(int index = 0;index<99;index++)
        {
            m_SerialPort->write(&fileTmp.constData()[index*tony],tony);
        }
        m_SerialPort->write(&fileTmp.constData()[99*tony],fileTmp.length() - 99*tony);
        file.close();
    }
}


